package com.example.wiki.service;

import com.example.wiki.domain.Ebook;
import com.example.wiki.domain.EbookExample;
import com.example.wiki.mapper.EbookMapper;
import com.example.wiki.req.EbookReq;
import com.example.wiki.req.EbookSaveReq;
import com.example.wiki.resp.EbookResp;
import com.example.wiki.resp.PageResp;
import com.example.wiki.util.CopyUtil;
import com.example.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class EbookService {
    private static final Logger Log = LoggerFactory.getLogger(EbookService.class);
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private EbookMapper ebookMapper;

    public PageResp<EbookResp> list(EbookReq req){

        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if(!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if(!ObjectUtils.isEmpty(req.getCategory2Id())){
            criteria.andCategory2IdEqualTo(req.getCategory2Id());
        }
        // 分页

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);

        Log.info("总数目:{}",pageInfo.getTotal());
        Log.info("总页数:{}",pageInfo.getPages());

        List<EbookResp> ebookRespList = CopyUtil.copyList(ebookList, EbookResp.class);
        PageResp<EbookResp> PageResp = new PageResp<>();
        PageResp.setTotal(pageInfo.getTotal());
        PageResp.setList(ebookRespList);
        return PageResp;
    }
    public void save(EbookSaveReq e){
        try{
            Ebook ebook = CopyUtil.copy(e,Ebook.class);
            if(ObjectUtils.isEmpty(e.getId())){
                e.setId(snowFlake.nextId());
                ebookMapper.insert(ebook);
            } else {
                ebookMapper.updateByPrimaryKey(ebook);
            }

        }catch (Exception exception){
            exception.printStackTrace();

        }

    }
    public int del(Long id){
        int i = ebookMapper.deleteByPrimaryKey(id);
        return i;
    }
}
